// Catch-all docs router. Renders the localized content for any
// `/docs/<path>` URL (and its `/de/docs/<path>` mirror). `getStaticPaths`
// enumerates the doc tree at build time so every page is pre-rendered.
//
// Bilingual (Strategy B): the doc SLUG is stable across locales — only the
// /de URL prefix differs — so each entry carries a `titleKey` / `bodyKey`
// into the message catalog rather than literal, one-language strings. The
// [locale] mirror (src/pages/[locale]/docs/[...slug].tsx) re-exports this
// page and emits the cross-product of non-default locales × these slugs.

import type { ReactNode } from 'react'
import type { PageMeta } from '@voltro/web'
import { useParams } from '@voltro/web'
import { T, useTFn } from '@voltro/i18n'
import { getCatalog, type Messages } from '../../../lib/locale'

export const renderMode = 'static' as const
export const interactive = 'none' as const

interface DocEntry {
  readonly slug: string
  readonly titleKey: keyof Messages
  readonly bodyKey: keyof Messages
}

// The doc tree — slugs stay identical across locales; the per-locale prose
// lives in the catalogs. Replace with a loader over a markdown folder / CMS
// / database query; the shape stays the same.
export const DOCS: ReadonlyArray<DocEntry> = [
  { slug: 'intro/getting-started', titleKey: 'docs.getting-started.title', bodyKey: 'docs.getting-started.body' },
  { slug: 'guides/first-page',     titleKey: 'docs.first-page.title',      bodyKey: 'docs.first-page.body' },
]

// getStaticPaths returns `{ params: { slug: '<path>' } }` entries — the
// framework substitutes each into `/docs/[...slug]` to enumerate the URLs
// to pre-render. The captured slug is the raw `/`-joined path (NOT a string
// array) so a single deep slug like 'intro/getting-started' renders one file.
export const getStaticPaths = async (): Promise<Array<{ params: { slug: string } }>> =>
  DOCS.map((d) => ({ params: { slug: d.slug } }))

// Per-locale, per-doc <title>: reads the active locale + the captured slug
// (both threaded in at SSG time) so each variant's head is localised.
export const meta = ({
  locale,
  params,
}: {
  locale: string
  params: Readonly<Record<string, string>>
}): PageMeta => {
  const c = getCatalog(locale)
  const doc = DOCS.find((d) => d.slug === params.slug)
  return {
    title: doc ? c[doc.titleKey] : c['docs.notFound.title'],
    description: c['meta.docs.description'],
  }
}

const code = (chunks: ReactNode): ReactNode => <code>{chunks}</code>

export default function DocPage(): ReactNode {
  const { slug } = useParams<{ slug: string }>()
  const t = useTFn()
  const doc = DOCS.find((d) => d.slug === slug)
  if (!doc) {
    return (
      <article>
        <h1>
          <T id="docs.notFound.title" />
        </h1>
        <p>
          <T id="docs.notFound.body" values={{ slug, code }} />
        </p>
      </article>
    )
  }
  return (
    <article>
      <h1>{t(doc.titleKey)}</h1>
      <p>{t(doc.bodyKey)}</p>
    </article>
  )
}
